package com.xinyue.game.gateway.server.socket;

import com.xinyue.game.gateway.common.GameGatewayMessageResponseHeader;
import com.xinyue.game.message.GameServerMessageModel;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 游戏网络通信编码Handler，负责处理向网络层发送消息之前，将消息序列化为ByteBuf
 *
 * @Author 王广帅
 * @Date 2021/5/30 19:12
 */
public class SocketEncoderHandler extends ChannelOutboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(SocketEncoderHandler.class);


    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        try {
            GameServerMessageModel<GameGatewayMessageResponseHeader> gatewayMessageWrapper = (GameServerMessageModel<GameGatewayMessageResponseHeader>) msg;
            GameGatewayMessageResponseHeader header = gatewayMessageWrapper.getHeader();
            int size = 4 + header.getHeaderSize();
            if (gatewayMessageWrapper.getBody() != null) {
                size += gatewayMessageWrapper.getBody().readableBytes();
            }
            ByteBuf byteBuf = Unpooled.buffer(size);
            byteBuf.writeInt(size);
            // 写入包头信息
            header.write(byteBuf);
            if (gatewayMessageWrapper.getBody() == null) {
                ctx.writeAndFlush(byteBuf, promise);
            } else {
                ByteBuf newBuf = Unpooled.wrappedBuffer(byteBuf, gatewayMessageWrapper.getBody());
                ctx.writeAndFlush(newBuf, promise);
            }
            logger.debug("网关返回消息,size: {}, header: {}", size, header);
        } catch (Throwable e) {
            logger.error("网关消息返回序列化失败", e);
        }

    }

}
